package com.ark.frigate.mybatis.dao;

import com.ark.frigate.mybatis.common.CommonExecute;
import com.ark.frigate.mybatis.config.ConfigHandler;
import com.ark.frigate.mybatis.config.Constant;
import com.ark.frigate.mybatis.utils.ColumnType;
import com.ark.frigate.mybatis.utils.DbConn;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 2016年11月7日 下午5:06:12 负责提供入口读取数据库表，并调用核心逻辑
 *
 * @author Along
 */
public class BuildDaoExecute extends CommonExecute {

    private static Logger logger = LoggerFactory.getLogger(BuildDaoExecute.class);

    private BuildHandle buildHandle;

    public BuildDaoExecute(ConfigHandler configHandler) {
        if (configHandler == null) {
            throw new RuntimeException("生成规则没有配置.");
        }
        this.configHandler = configHandler;
        buildHandle = new BuildHandle(configHandler.getStrategyConfig());
    }

    public BuildDaoExecute(String entityClass, String interfaceClass, String xmlMapper) {

        buildHandle = new BuildHandle(entityClass, interfaceClass, xmlMapper);
    }

    @Override
    public void start() throws ClassNotFoundException, SQLException {

        String prefix = "show full fields from ";
        List<String> columns;
        List<String> types;
        List<String> comments;
        PreparedStatement prepare = null;
        ResultSet results = null;
        List<String> tables = getTables();
        Map<String, String> tableComments = getTableComment();

        String includeTable = "," + configHandler.getStrategyConfig().getIncludeTable() + ",";
        String ignoreTable = "," + configHandler.getStrategyConfig().getIgnoreTable() + ",";
        try {
            for (String table : tables) {
                // 指定表
                if (!",all,".equals(includeTable) && !includeTable.contains("," + table + ",")) {
                    continue;
                }
                // 排除表
                if (!",no,".equals(ignoreTable) && ignoreTable.contains("," + table + ",")) {
                    continue;
                }
                columns = new ArrayList<String>();
                types = new ArrayList<String>();
                comments = new ArrayList<String>();

                if (ColumnType.keyWords().contains(table)) {
                    prepare = DbConn.getConn().prepareStatement(prefix + ColumnType.KEY + table + ColumnType.KEY);
                } else {
                    prepare = DbConn.getConn().prepareStatement(prefix + table);
                }
                results = prepare.executeQuery();
                while (results.next()) {
                    columns.add(results.getString("FIELD"));
                    types.add(results.getString("TYPE"));
                    comments.add(results.getString("COMMENT"));
                }

                Map<String, Object> map = getNamesDao(table, "Dao");
                String tableComment = tableComments.get(table);
                buildHandle.buildEntityBean(columns, types, comments, tableComment, map.get(Constant.BEAN_NAME).toString());
                buildHandle.buildDao(map.get(Constant.BEAN_NAME).toString(), map.get(Constant.DAO_NAME).toString());
                buildHandle.buildMapperXml(columns, types, table, map.get(Constant.BEAN_NAME).toString(),
                        map.get(Constant.MAPPER_NAME).toString(), null);
            }
            results.close();
            prepare.close();
        } catch (Exception e) {
            logger.error("创建myBatis相关信息异常", e);
            if (null != results) {
                results.close();
            }
            if (prepare != null) {
                prepare.close();
            }
            DbConn.getConn().close();
        }
    }

}
